package com.chaoxi.picturebackend.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.chaoxi.picturebackend.annotation.AuthCheck;
import com.chaoxi.picturebackend.common.BaseResponse;
import com.chaoxi.picturebackend.common.DeleteBatchRequest;
import com.chaoxi.picturebackend.common.DeleteRequest;
import com.chaoxi.picturebackend.common.ResultUtils;
import com.chaoxi.picturebackend.constant.UserConstant;

import com.chaoxi.picturebackend.exception.ErrorCode;
import com.chaoxi.picturebackend.exception.ThrowUtils;
import com.chaoxi.picturebackend.model.dto.category.CategoryAddRequest;
import com.chaoxi.picturebackend.model.dto.category.CategoryEditRequest;
import com.chaoxi.picturebackend.model.dto.category.CategoryQueryRequest;
import com.chaoxi.picturebackend.model.dto.category.CategoryUpdateRequest;
import com.chaoxi.picturebackend.model.entity.PictureCategory;
import com.chaoxi.picturebackend.model.entity.User;
import com.chaoxi.picturebackend.service.PictureCategoryService;
import com.chaoxi.picturebackend.service.UserService;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/category")
@RequiredArgsConstructor
public class PictureCategoryController {

    @Resource
    private PictureCategoryService pictureCategoryService;

    @Resource
    private UserService userService;

    /**
     * 创建分类
     */
    @PostMapping("/add")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    @ApiOperation("创建分类")
    public BaseResponse<Long> addCategory(@RequestBody CategoryAddRequest categoryAddRequest, HttpServletRequest request) {
        ThrowUtils.throwIf(categoryAddRequest == null, ErrorCode.PARAMS_ERROR);
        
        PictureCategory pictureCategory = new PictureCategory();
        BeanUtils.copyProperties(categoryAddRequest, pictureCategory);
        
        // 设置创建信息
        User loginUser = userService.getLoginUser(request);
        pictureCategory.setCreateUser(loginUser.getId());
        pictureCategory.setCreateTime(new Date());
        pictureCategory.setUpdateTime(new Date());
        pictureCategory.setIsDelete(0);
        
        // 数据校验
        validCategory(pictureCategory);
        
        // 保存到数据库
        boolean result = pictureCategoryService.save(pictureCategory);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        
        // 清除分类缓存
        pictureCategoryService.clearCategoryCache();
        
        return ResultUtils.success(pictureCategory.getId());
    }

    /**
     * 删除分类
     */
    @PostMapping("/delete")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    @ApiOperation("删除分类")
    public BaseResponse<Boolean> deleteCategory(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        ThrowUtils.throwIf(deleteRequest == null, ErrorCode.PARAMS_ERROR);
        long id = deleteRequest.getId();
        // 判断是否存在
        PictureCategory oldCategory = pictureCategoryService.getById(id);
        ThrowUtils.throwIf(oldCategory == null, ErrorCode.NOT_FOUND_ERROR);
        // 操作数据库
        boolean result = pictureCategoryService.removeById(id);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        
        // 清除分类缓存
        pictureCategoryService.clearCategoryCache();
        
        return ResultUtils.success(true);
    }

    /**
     * 批量删除分类
     */
    @PostMapping("/delete/batch")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    @ApiOperation("批量删除分类")
    public BaseResponse<Boolean> deleteCategoryBatch(@RequestBody DeleteBatchRequest deleteRequest, HttpServletRequest request) {
        ThrowUtils.throwIf(deleteRequest == null || deleteRequest.getId() == null || deleteRequest.getId().isEmpty(),
                ErrorCode.PARAMS_ERROR, "请选择要删除的分类");

        List<Long> ids = deleteRequest.getId();

        // 检查所有分类是否存在
        for (Long id : ids) {
            PictureCategory oldCategory = pictureCategoryService.getById(id);
            ThrowUtils.throwIf(oldCategory == null, ErrorCode.NOT_FOUND_ERROR, "分类不存在: " + id);
        }

        // 执行批量删除
        boolean result = pictureCategoryService.removeByIds(ids);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR, "删除失败");

        // 清除分类缓存
        pictureCategoryService.clearCategoryCache();

        return ResultUtils.success(true);
    }

    /**
     * 更新分类（管理员）
     */
    @PostMapping("/update")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    @ApiOperation("更新分类（管理员）")
    public BaseResponse<Boolean> updateCategory(@RequestBody CategoryUpdateRequest categoryUpdateRequest, HttpServletRequest request) {
        ThrowUtils.throwIf(categoryUpdateRequest == null || categoryUpdateRequest.getId() == null, ErrorCode.PARAMS_ERROR);
        
        // 判断是否存在
        long id = categoryUpdateRequest.getId();
        PictureCategory oldCategory = pictureCategoryService.getById(id);
        ThrowUtils.throwIf(oldCategory == null, ErrorCode.NOT_FOUND_ERROR);
        
        // 更新对象
        PictureCategory pictureCategory = new PictureCategory();
        BeanUtils.copyProperties(categoryUpdateRequest, pictureCategory);
        pictureCategory.setUpdateTime(new Date());
        
        // 数据校验
        validCategory(pictureCategory);
        
        // 操作数据库
        boolean result = pictureCategoryService.updateById(pictureCategory);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        
        // 清除分类缓存
        pictureCategoryService.clearCategoryCache();
        
        return ResultUtils.success(true);
    }

    /**
     * 根据 id 获取分类
     */
    @GetMapping("/get")
    @ApiOperation("根据 id 获取分类")
    public BaseResponse<PictureCategory> getCategoryById(long id) {
        ThrowUtils.throwIf(id <= 0, ErrorCode.PARAMS_ERROR);
        
        PictureCategory pictureCategory = pictureCategoryService.getById(id);
        ThrowUtils.throwIf(pictureCategory == null, ErrorCode.NOT_FOUND_ERROR);
        ThrowUtils.throwIf(pictureCategory.getIsDelete() == 1, ErrorCode.NOT_FOUND_ERROR, "分类已被删除");
        
        return ResultUtils.success(pictureCategory);
    }

    /**
     * 分页获取分类列表
     */
    @PostMapping("/list/page")
    @ApiOperation("分页获取分类列表")
    public BaseResponse<Page<PictureCategory>> listCategoryByPage(@RequestBody CategoryQueryRequest categoryQueryRequest) {
        long current = categoryQueryRequest.getCurrent();
        long size = categoryQueryRequest.getPageSize();
        
        // 查询数据库
        QueryWrapper<PictureCategory> queryWrapper = getQueryWrapper(categoryQueryRequest);
        Page<PictureCategory> categoryPage = pictureCategoryService.page(new Page<>(current, size), queryWrapper);
        
        return ResultUtils.success(categoryPage);
    }

    /**
     * 获取所有分类列表（不分页）
     */
    @PostMapping("/list")
    @ApiOperation("获取所有分类列表")
    public BaseResponse<List<PictureCategory>> listCategory() {
        List<PictureCategory> categoryList = pictureCategoryService.list();
        return ResultUtils.success(categoryList);
    }

    /**
     * 编辑分类（用户）
     */
    @PostMapping("/edit")
    @ApiOperation("编辑分类")
    public BaseResponse<Boolean> editCategory(@RequestBody CategoryEditRequest categoryEditRequest, HttpServletRequest request) {
        ThrowUtils.throwIf(categoryEditRequest == null || categoryEditRequest.getId() == null, ErrorCode.PARAMS_ERROR);
        
        // 判断是否存在
        long id = categoryEditRequest.getId();
        PictureCategory oldCategory = pictureCategoryService.getById(id);
        ThrowUtils.throwIf(oldCategory == null, ErrorCode.NOT_FOUND_ERROR);
        
        // 更新对象
        PictureCategory pictureCategory = new PictureCategory();
        BeanUtils.copyProperties(categoryEditRequest, pictureCategory);
        pictureCategory.setUpdateTime(new Date());
        
        // 数据校验
        validCategory(pictureCategory);
        
        // 操作数据库
        boolean result = pictureCategoryService.updateById(pictureCategory);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        
        // 清除分类缓存
        pictureCategoryService.clearCategoryCache();
        
        return ResultUtils.success(true);
    }

    /**
     * 更新分类排序
     */
    @PostMapping("/update/sort")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    @ApiOperation("更新分类排序")
    public BaseResponse<Boolean> updateCategorySort(@RequestParam Long id, @RequestParam Integer sortOrder, HttpServletRequest request) {
        ThrowUtils.throwIf(id == null || sortOrder == null, ErrorCode.PARAMS_ERROR);
        
        PictureCategory category = pictureCategoryService.getById(id);
        ThrowUtils.throwIf(category == null, ErrorCode.NOT_FOUND_ERROR);
        
        category.setSortOrder(sortOrder);
        category.setUpdateTime(new Date());
        boolean result = pictureCategoryService.updateById(category);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        
        // 清除分类缓存
        pictureCategoryService.clearCategoryCache();
        
        return ResultUtils.success(true);
    }

    /**
     * 分类数据校验
     */
    private void validCategory(PictureCategory pictureCategory) {
        ThrowUtils.throwIf(pictureCategory == null, ErrorCode.PARAMS_ERROR);
        String categoryName = pictureCategory.getCategoryName();
        ThrowUtils.throwIf(categoryName == null || categoryName.trim().isEmpty(), ErrorCode.PARAMS_ERROR, "分类名称不能为空");
        ThrowUtils.throwIf(categoryName.length() > 50, ErrorCode.PARAMS_ERROR, "分类名称过长");
        
        Integer sortOrder = pictureCategory.getSortOrder();
        if (sortOrder != null) {
            ThrowUtils.throwIf(sortOrder < 0, ErrorCode.PARAMS_ERROR, "排序值不能为负数");
        }
    }

    /**
     * 获取查询条件
     */
    private QueryWrapper<PictureCategory> getQueryWrapper(CategoryQueryRequest categoryQueryRequest) {
        QueryWrapper<PictureCategory> queryWrapper = new QueryWrapper<>();
        if (categoryQueryRequest == null) {
            return queryWrapper;
        }
        
        Long id = categoryQueryRequest.getId();
        String categoryName = categoryQueryRequest.getCategoryName();
        String description = categoryQueryRequest.getDescription();
        String sortOrder = categoryQueryRequest.getSortOrder();
        String sortField = categoryQueryRequest.getSortField();

        // 构建查询条件
        queryWrapper.eq(id != null, "id", id);
        queryWrapper.like(categoryName != null, "categoryName", categoryName);
        queryWrapper.like(description != null, "description", description);
        queryWrapper.eq(sortOrder != null, "sortOrder", sortOrder);
        
        // 排序
        if (sortField != null) {
            queryWrapper.orderBy(true, "asc".equals(sortOrder), sortOrder);
        } else {
            queryWrapper.orderByAsc("sortOrder").orderByDesc("createTime");
        }
        
        return queryWrapper;
    }
}